﻿using DevExpress.XtraEditors;
using MESQWinform;
using Ces.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MesProjectWinform.BasicData.Entity;

namespace MesProjectWinform.BasicData.基础实现.chan
{
    public partial class chanup : DevExpress.XtraEditors.XtraForm
    {
        private List<WorkShop> workshopList;
        private long selectedWorkshopId;
        
        // 添加事件委托，用于通知主窗体数据已更新
        public delegate void DataUpdatedEventHandler();
        public event DataUpdatedEventHandler DataUpdated;
        
        // 保存当前产线ID
        private long _productionlineId;
        
        // 保存原始产线数据，用于重置功能
        private Productionline _originalProductionline;

        // 默认构造函数 - 用于新增产线
        public chanup()
        {
            InitializeComponent();
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;
            
            LoadWorkshops();
        }
        
        // 带参数的构造函数 - 用于修改产线
        public chanup(long id)
        {
            InitializeComponent();
            _productionlineId = id;
            
            // 加载表单时获取数据
            this.Load += Chanup_Load;
        }
        
        // 表单加载事件
        private async void Chanup_Load(object sender, EventArgs e)
        {
            await LoadWorkshops();
            await LoadProductionlineData();
        }
        
        // 从API加载产线数据
        private async Task LoadProductionlineData()
        {
            try
            {
                // 调用API获取产线数据
                string url = $"api/Productionline/GetProductionlineById?id={_productionlineId}";
                string json = await APIClientl.CallApiAsync(url);
                
                // 使用动态类型解析JSON，避免类型冲突
                dynamic result = JsonConvert.DeserializeObject<dynamic>(json);
                
                // 处理JSON数据，考虑可能的不同结构
                dynamic productionlineData = null;
                
                // 检查Data是否为数组
                if (result.Data is Newtonsoft.Json.Linq.JArray jArray && jArray.Count > 0)
                {
                    // 如果是数组，获取第一个元素
                    productionlineData = jArray[0];
                }
                else if (result.Data != null)
                {
                    // 如果不是数组，直接使用Data
                    productionlineData = result.Data;
                }
                
                if (productionlineData != null)
                {
                    // 创建产线对象，安全获取属性值
                    _originalProductionline = new Productionline
                    {
                        Id = GetDynamicValueOrDefault(productionlineData, "Id", 0L),
                        Productionlinecode = GetDynamicValueOrDefault(productionlineData, "Productionlinecode", string.Empty),
                        Productionlinename = GetDynamicValueOrDefault(productionlineData, "Productionlinename", string.Empty),
                        Productionlinedescription = GetDynamicValueOrDefault(productionlineData, "Productionlinedescription", string.Empty),
                        Workshopid = GetDynamicValueOrDefault(productionlineData, "Workshopid", string.Empty),
                        Workshopname = GetDynamicValueOrDefault(productionlineData, "Workshopname", string.Empty),
                        Productionlineattributes = GetDynamicValueOrDefault(productionlineData, "Productionlineattributes", string.Empty),
                        IsDeleted = GetDynamicValueOrDefault(productionlineData, "IsDeleted", false),
                        CreatedBy = GetDynamicValueOrDefault(productionlineData, "CreatedBy", string.Empty),
                        CreatedTime = GetDynamicValueOrDefault(productionlineData, "CreatedTime", DateTime.Now),
                        UpdatedBy = GetDynamicValueOrDefault(productionlineData, "UpdatedBy", string.Empty),
                        UpdatedTime = GetDynamicValueOrDefault(productionlineData, "UpdatedTime", DateTime.Now)
                    };
                    
                    // 将数据显示到表单控件中
                    DisplayProductionlineData(_originalProductionline);
                }
                else
                {
                    XtraMessageBox.Show("未找到产线数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }
        
        /// <summary>
        /// 安全获取动态对象的属性值
        /// </summary>
        /// <typeparam name="T">属性值类型</typeparam>
        /// <param name="obj">动态对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>属性值或默认值</returns>
        private T GetDynamicValueOrDefault<T>(dynamic obj, string propertyName, T defaultValue)
        {
            try
            {
                if (obj == null)
                    return defaultValue;
                    
                // 检查是否为JObject类型
                if (obj is Newtonsoft.Json.Linq.JObject jObject)
                {
                    if (jObject.ContainsKey(propertyName))
                    {
                        try
                        {
                            return jObject[propertyName].ToObject<T>();
                        }
                        catch
                        {
                            return defaultValue;
                        }
                    }
                    return defaultValue;
                }
                
                // 尝试通过反射获取属性值
                var property = obj.GetType().GetProperty(propertyName);
                if (property == null)
                    return defaultValue;
                    
                var value = property.GetValue(obj, null);
                if (value == null)
                    return defaultValue;
                    
                // 尝试转换类型
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    return defaultValue;
                }
            }
            catch
            {
                return defaultValue;
            }
        }
        
        // 将产线数据显示到表单控件中
        private void DisplayProductionlineData(Productionline productionline)
        {
            // 设置窗体标题
            this.Text = $"修改产线 - {productionline.Productionlinename}";
            
            // 显示产线信息到相应控件
            // 注意：这里假设表单中有对应的控件，实际使用时需要根据实际控件名称调整
            if (textEdit1 != null) 
            {
                textEdit1.Text = productionline.Productionlinecode;  // 产线编码
                // 设置编号文本框为只读，因为编号是自动生成的不可修改
                textEdit1.Properties.ReadOnly = true;
            }
            if (textEdit2 != null) textEdit2.Text = productionline.Productionlinename;  // 产线名称
            if (memoEdit1 != null) memoEdit1.Text = productionline.Productionlinedescription;  // 产线描述
            
            // 设置车间下拉框选中项
            SetSelectedWorkshop(productionline.Workshopid);
        }
        
        // 设置车间下拉框选中项
        private void SetSelectedWorkshop(string workshopId)
        {
            if (workshopList != null && workshopList.Count > 0 && !string.IsNullOrEmpty(workshopId))
            {
                try
                {
                    // 尝试解析workshopId为长整型
                    long workshopIdLong;
                    bool parseSuccess = long.TryParse(workshopId, out workshopIdLong);
                    
                    // 查找匹配的车间
                    for (int i = 0; i < workshopList.Count; i++)
                    {
                        if ((parseSuccess && workshopList[i].Id == workshopIdLong) || 
                            workshopList[i].Id.ToString() == workshopId)
                        {
                            comboBox1.SelectedIndex = i;
                            // 保存选中的车间ID
                            selectedWorkshopId = workshopList[i].Id;
                            break;
                        }
                    }
                }
                catch
                {
                    // 如果有任何异常，尝试使用第一个车间
                    if (workshopList.Count > 0)
                    {
                        comboBox1.SelectedIndex = 0;
                        selectedWorkshopId = workshopList[0].Id;
                    }
                }
            }
        }

       /// <summary>
       /// 下拉获取渠道
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.SelectedIndex >= 0 && workshopList != null && workshopList.Count > comboBox1.SelectedIndex)
                {
                    // 获取选中的车间对象
                    WorkShop selectedWorkshop = workshopList[comboBox1.SelectedIndex];
                    // 保存选中车间的ID
                    selectedWorkshopId = selectedWorkshop.Id;
                    // 更新标签显示车间名称
                    labelControl3.Text = $"车间名称: {selectedWorkshop.Workshopname}";
                }
            }
            catch (Exception ex)
            {
                // 捕获并记录异常，但不中断用户操作
                System.Diagnostics.Debug.WriteLine($"车间选择错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载所有车间数据
        /// </summary>
        private async Task LoadWorkshops()
        {
            try
            {
                // 调用API获取所有车间数据
                string response = await APIClientl.CallApiAsync("api/WorkShop/GetAllShop", "GET");
                
                // 使用动态类型解析JSON数据，避免类型转换问题
                dynamic result = JsonConvert.DeserializeObject<dynamic>(response);
                
                if (result != null && result.Data != null)
                {
                    // 创建车间列表
                    workshopList = new List<WorkShop>();
                    
                    // 解析JSON数据到车间列表
                    if (result.Data is Newtonsoft.Json.Linq.JArray)
                    {
                        foreach (var item in result.Data)
                        {
                            WorkShop workshop = new WorkShop
                            {
                                Id = item.Id,
                                Workshopcode = item.Workshopcode?.ToString(),
                                Workshopname = item.Workshopname?.ToString(),
                                Workshopdescription = item.Workshopdescription?.ToString()
                            };
                            workshopList.Add(workshop);
                        }
                    }
                    
                    // 清空下拉框
                    comboBox1.Items.Clear();
                    
                    // 将车间名称添加到下拉框
                    foreach (var workshop in workshopList)
                    {
                        comboBox1.Items.Add(workshop.Workshopname);
                    }
                    
                    // 如果有数据，默认选择第一项
                    if (comboBox1.Items.Count > 0 && _productionlineId == 0)
                    {
                        comboBox1.SelectedIndex = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取车间数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 获取当前选中的车间ID
        /// </summary>
        /// <returns>车间ID</returns>
        public long GetSelectedWorkshopId()
        {
            return selectedWorkshopId;
        }
        
        /// <summary>
        /// 获取当前选中的车间名称
        /// </summary>
        /// <returns>车间名称</returns>
        public string GetSelectedWorkshopName()
        {
            return comboBox1.SelectedItem?.ToString();
        }
        
        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private async void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建产线对象
                Productionline productionline;
                
                if (_productionlineId > 0)
                {
                    // 修改现有产线
                    productionline = new Productionline
                    {
                        Id = _productionlineId,
                        IsDeleted = _originalProductionline.IsDeleted,
                        CreatedBy = _originalProductionline.CreatedBy,
                        CreatedTime = _originalProductionline.CreatedTime,
                        UpdatedBy = _originalProductionline.UpdatedBy,
                        UpdatedTime = DateTime.Now
                    };
                }
                else
                {
                    // 新增产线
                    productionline = new Productionline
                    {
                        CreatedTime = DateTime.Now,
                        UpdatedTime = DateTime.Now,
                        IsDeleted = false
                    };
                }
                
                // 设置产线信息
                productionline.Productionlinecode = textEdit1.Text.Trim();
                productionline.Productionlinename = textEdit2.Text.Trim();
                productionline.Productionlinedescription = memoEdit1.Text.Trim();
                productionline.Workshopid = selectedWorkshopId.ToString();
                productionline.Workshopname = GetSelectedWorkshopName();
                
                // 将对象转换为JSON
                string jsonData = JsonConvert.SerializeObject(productionline);
                
                // 调用API保存数据
                string url = _productionlineId > 0 ? "api/Productionline/UpdateProductionline" : "api/Productionline/AddProductionline";
                string result = await APIClientl.CallApiAsync(url, "POST", jsonData);
                
                // 解析返回结果
                var response = JsonConvert.DeserializeObject<dynamic>(result);
                
                if (response != null && response.Code == "200")
                {
                    XtraMessageBox.Show(_productionlineId > 0 ? "修改成功" : "添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 触发数据更新事件
                    OnDataUpdated();
                    
                    // 关闭窗体
                    this.Close();
                }
                else
                {
                    string errorMsg = response != null ? response.Message.ToString() : "未知错误";
                    XtraMessageBox.Show($"操作失败: {errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private void btnReset_Click(object sender, EventArgs e)
        {
            if (_productionlineId > 0 && _originalProductionline != null)
            {
                // 重新显示原始数据，恢复到初始状态
                DisplayProductionlineData(_originalProductionline);
            }
            else
            {
                // 清空所有输入框
                textEdit1.Text = string.Empty;
                textEdit2.Text = string.Empty;
                memoEdit1.Text = string.Empty;
                
                // 重置下拉框选择
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
        }
        
        // 触发数据更新事件的方法
        protected void OnDataUpdated()
        {
            DataUpdated?.Invoke();
        }
        /// <summary>
        /// 修改产线信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建更新对象，保留原始数据的ID和其他必要字段
                Productionline updatedProductionline = new Productionline
                {
                    Id = _originalProductionline.Id,
                    IsDeleted = _originalProductionline.IsDeleted,
                    CreatedBy = _originalProductionline.CreatedBy,
                    CreatedTime = _originalProductionline.CreatedTime,  // 保留原始创建时间
                    UpdatedBy = "张三",
                    UpdatedTime = DateTime.Now,  // 更新修改时间
                    
                    // 从控件获取更新后的值
                    Productionlinecode = textEdit1.Text.Trim(),
                    Productionlinename = textEdit2.Text.Trim(),
                    Productionlinedescription = memoEdit1.Text.Trim(),
                    Workshopid = selectedWorkshopId.ToString(),
                    Workshopname = comboBox1.Text.Trim(),
                    Productionlineattributes = " "  // 保留原始值
                };
                
                // 将对象转换为JSON
                string jsonData = JsonConvert.SerializeObject(updatedProductionline);
                
                // 调用API更新数据，使用POST请求
                string url = "api/Productionline/UpdateProductionline";
                string result = await APIClientl.CallApiAsync(url, "POST", jsonData);
                
                // 解析返回结果
                var response = JsonConvert.DeserializeObject<dynamic>(result);
                
                if (response != null && response.Code == "200")
                {
                    XtraMessageBox.Show("修改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 触发数据更新事件
                    OnDataUpdated();
                    
                    // 关闭窗体
                    this.Close();
                }
                else
                {
                    string errorMsg = response != null ? response.Message.ToString() : "未知错误";
                    XtraMessageBox.Show($"修改失败: {errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}